import router from './router'
import axios from 'axios'
import Cookies from 'js-cookie'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { Modal } from 'ant-design-vue'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

function disT(T) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      timeout: 180000,
      headers: {
        GF: '1',
        Authorization: 'bearer' + ' ' + T,
      },
      url: process.env.VUE_APP_API_BASE_URL_BZF + '/api/TontenDisplay/Validation',
    })
      .then((res) => {
        resolve(res.data)
      })
      .catch(() => {
        Modal.info({
          title: '提示',
          content: '请前往登录后访问',
          onOk() {
            window.location.href = 'http://222.85.201.115:8029/login'
          },
        })
      })
  })
}

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`)
  /* has token */
  if (to.query.T) {
    axios({
      method: 'get',
      timeout: 180000,
      headers: {
        GF: '1',
      },
      params: {
        MD5: to.query.T,
      },
      url: process.env.VUE_APP_API_BASE_URL_BZF + '/api/TontenDisplay/GetToken',
    }).then((res) => {
      Cookies.set('ACCESS_TOKEN', res.data.msg)
      disT(res.data.msg).then((d) => {
        next()
        NProgress.done()
      })
    })
  } else if (Cookies.get('ACCESS_TOKEN')) {
    disT(Cookies.get('ACCESS_TOKEN')).then((d) => {
      next()
      NProgress.done()
    })
  } else {
    Modal.info({
      title: '提示',
      content: '请前往登录后访问',
      onOk() {
        window.location.href = 'http://222.85.201.115:8029/login'
      },
    })
  }
})

router.afterEach(() => {
  // window.scrollTo(0, 0)
  NProgress.done() // finish progress bar
})
